import { ElMessage } from "element-plus";

export function initWebSocket(id: number) {
  const webSocket: WebSocket = new WebSocket(
    "ws://localhost:8081/websocket/" + id
  );

  webSocket.onopen = () => {
    console.log("websocket连接成功");
  };
  webSocket.onclose = () => {
    console.log("websocket连接关闭");
  };
  webSocket.onerror = () => {
    ElMessage.error("websocket连接异常");
  };
  webSocket.onmessage = (event) => {
    // 自定义全局监听事件
    window.dispatchEvent(
      new CustomEvent("onmessageWS", {
        detail: {
          data: event.data,
        },
      })
    );
    //
  };
  return webSocket;
}
